package controllers

import (
	"Zice/cache"
	"Zice/models"
	"encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"time"
)

type YueController struct {
	beego.Controller
}
type Pagecount struct {
	Data  interface{} `json:"data"`
	Count int64
}

func (c *YueController) Lists() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	keyword := c.GetString("keyword")
	page, _ := c.GetInt("page")
	pageSize, _ := c.GetInt("pageSize")

	var yue models.Yuedu
	var lists []*models.Yuedu

	key := fmt.Sprintf("yue_error_%s_%d", keyword, page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, key).Result()

	if cacheData == "" {
		lists, _ = yue.Lists(keyword, page, pageSize)
		if len(lists) != 0 {
			jsonData, _ := json.Marshal(lists)
			cache.Rdb.Set(cache.Ctx, key, jsonData, time.Hour*24)
		}
	} else {
		fmt.Println("获取成功")
		json.Unmarshal([]byte(cacheData), &lists)
	}

	c.Data["json"] = Res{
		Code: 200,
		Msg:  "查询成功",
		Data: lists,
	}
	c.ServeJSON()
	return
}

func (c *YueController) Del() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")

	var err error
	id, _ := c.GetInt("id")
	var yue models.Yuedu
	yue.ID = uint(id)

	if err = yue.Get(); err != nil {
		c.Data["json"] = Res{
			Code: 500,
			Msg:  "系统错误",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	if err = yue.Del(); err != nil {
		c.Data["json"] = Res{
			Code: 500,
			Msg:  "系统错误",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	if yue.Status == 1 {
		c.Data["json"] = Res{
			Code: 500,
			Msg:  "已阅读的禁止删除",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	key := fmt.Sprintf("yue_error_%d", yue.ID)
	cache.Rdb.Del(cache.Ctx, key)

	c.Data["json"] = Res{
		Code: 200,
		Msg:  "删除成功",
		Data: nil,
	}
	c.ServeJSON()
	return
}
